
use crate::{IResult, JsonV};
use serde::de::DeserializeOwned;
use serde_json::Map;
use std::fmt::Debug;

use super::extend::StringExentd;

pub trait JsonVExentd {
    fn as_string2(&self) -> Option<String>;

    fn as_arrary2(&self) -> Option<Vec<JsonV>>;

    fn as_object2(&self) -> Option<serde_json::Map<String, JsonV>>;
}

impl JsonVExentd for JsonV {
    fn as_string2(&self) -> Option<String> {
        match self {
            JsonV::String(v) => Some(v.to_string()),
            _ => None,
        }
    }

    fn as_arrary2(&self) -> Option<Vec<JsonV>> {
        match self {
            JsonV::Array(v) => Some(v.clone()),
            _ => None,
        }
    }

    fn as_object2(&self) -> Option<Map<String, JsonV>> {
        match self {
            JsonV::Object(v) => Some(v.clone()),
            _ => None,
        }
    }
}

pub trait SerdejsonExentd {
    fn get_json_field<R: DeserializeOwned + Debug>(input_data: &Option<JsonV>, k: &str) -> IResult<R>;

    /// 获得字段数据
    fn get_json_field2(&self, k: &str) -> IResult<JsonV>;
}

impl SerdejsonExentd for &str {
    fn get_json_field<R: DeserializeOwned + Debug>(json_value: &Option<JsonV>, k: &str) -> IResult<R> {
        String::get_json_field(json_value, k)
    }

    fn get_json_field2(&self, k: &str) -> IResult<JsonV> {
        let mut v = serde_json::from_str::<JsonV>(self)?;
        let k_arr = k.split_arr(".");
        for x in k_arr {
            if x.trim() == "" {
                continue;
            }
            v = v[x].to_owned();
        }
        Ok(v)
    }
}

impl SerdejsonExentd for String {
    fn get_json_field<R: DeserializeOwned + Debug>(json_value: &Option<JsonV>, k: &str) -> IResult<R> {
        let r = json_value
            .as_ref()
            .ok_or(format!("[{}]数据为空", k))?
            .as_object()
            .ok_or(format!("[{}]反序列化为JSON对象时出错", k))?
            .get(k)
            .ok_or_else(|| format!("[{}]JSON中没有数据", k))
            .map(|v| serde_json::from_value::<R>(v.clone()).map_err(|e| format!("[{}]序列化为struct出错,{:?}", k, e)))??;
        debug!("获得[{}]JSON数据, 返回: {:?}", k, &r);
        Ok(r)
    }

    fn get_json_field2(&self, k: &str) -> IResult<JsonV> {
        self.as_str().get_json_field2(k)
    }
}

#[test]
fn test_json() {
    let r = r##"{"k": {"k2": 345}, "k1": 123}"##.get_json_field2("k");
    println!("{:?}", r);
}

/// 获得json对象的值
pub fn get_json_string(json_map: &serde_json::Map<String, JsonV>, key: &str) -> IResult<String> {
    let name = json_map.get(key).ok_or(format!("获得[{}]发生错误", key))?;
    let name = name.as_str().ok_or(format!("获得[{}]序列化为字符串发生错误", key).as_str())?;
    Ok(name.to_string())
}


/// 合并数据
pub fn marge_obj_data<T: serde::Serialize, T2: serde::Serialize + DeserializeOwned>(
    src: &T,
    tager_input: &mut T2,
) -> IResult {
    let src = serde_json::to_value(src)?;
    let tager = serde_json::to_string(tager_input)?;
    let mut tager = serde_json::from_str::<JsonV>(&tager)?;
    if let (Some(src), Some(tager)) = (src.as_object(), tager.as_object_mut()) {
        let src = src.clone();
        for (k, v) in src {
            if !v.is_null(){
                tager.insert(k, v);
            }
        }
    }
    let t2 = serde_json::from_value::<T2>(tager)?;
    *tager_input = t2;
    Ok(())
}